package com.hotel.auth.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class JwtService {

    @Value("${jwt.secret:#{null}}")
    private String secret;

    @Value("${jwt.issuer:hotel-cloud}")
    private String issuer;

    @Value("${jwt.access-token-ttl-minutes:60}")
    private long accessTtlMinutes;

    @Value("${jwt.refresh-token-ttl-days:7}")
    private long refreshTtlDays;

    private SecretKey getKey() {
        if (secret == null || secret.length() < 32) {
            throw new IllegalStateException("jwt.secret 未配置或长度不足，需在 Nacos jwt.yaml 提供长度≥32的ASCII密钥");
        }
        return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    public String generateAccessToken(Long userId, List<String> permissions) {
        Instant now = Instant.now();
        return Jwts.builder()
                .setIssuer(issuer)
                .setSubject(String.valueOf(userId))
                .setIssuedAt(Date.from(now))
                .setExpiration(Date.from(now.plus(accessTtlMinutes, ChronoUnit.MINUTES)))
                .addClaims(Map.of(
                        "uid", userId,
                        "perms", permissions
                ))
                .signWith(getKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public String generateRefreshToken(Long userId) {
        Instant now = Instant.now();
        return Jwts.builder()
                .setIssuer(issuer)
                .setSubject(String.valueOf(userId))
                .setIssuedAt(Date.from(now))
                .setExpiration(Date.from(now.plus(refreshTtlDays, ChronoUnit.DAYS)))
                .addClaims(Map.of("uid", userId))
                .signWith(getKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public Claims parse(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}


